package com.echo.week.server;

/**
 * @Author echo
 * @Description 网站服务器案例--线程池+ 配置文件读取端口
 * @Date 2023/10/22.
 * @Version 1.0
 */

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * 线程池 + 配置文件读取端口
 */
public class BsServer04 {
    public static void main(String[] args) throws DocumentException, IOException {
        //初始化端口
        //读取配置文件Server.xml中的端口号
        InputStream in = BsServer04.class.getClassLoader().getResourceAsStream("server.xml");
        //获取配置文件输入流
        SAXReader saxReader = new SAXReader();
        Document doc = saxReader.read(in);
        //使用SAXReader + XPath读取端口配置
        Element portEle = (Element) doc.selectSingleNode("//port");
        String port = portEle.getText();

        System.out.println("服务器 启动.....  ");
        System.out.println("开启端口 : " + Integer.valueOf(port));
        //启动web服务
        ServerSocket server = new ServerSocket(Integer.valueOf(port));
        //线程池
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        while(true){
            Socket socket = server.accept();
            //提交一个任务
            executorService.submit(()->{
                try{
                    //转换流,读取浏览器请求第一行
                    BufferedReader readWb = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    String requst = readWb.readLine();
                    //取出请求资源的路径
                    String[] strArr = requst.split(" ");
                    System.out.println(Arrays.toString(strArr));
                    String path = strArr[1].substring(1);
                    System.out.println(path);

                    FileInputStream fis = new FileInputStream(path);
                    System.out.println(fis);
                    byte[] bytes= new byte[1024];
                    int len = 0 ;

                    //向浏览器 回写数据
                    OutputStream out = socket.getOutputStream();
                    out.write("HTTP/1.1 200 OK\r\n".getBytes());
                    out.write("Content-Type:text/html\r\n".getBytes());
                    out.write("\r\n".getBytes());
                    while((len = fis.read(bytes))!=-1){
                        out.write(bytes,0,len);
                    }
                    fis.close();
                    out.close();
                    readWb.close();
                    socket.close();
                }catch(Exception ex){
                    ex.printStackTrace();
                }
            });
        }
    }
}